<template>
  <a-card :bordered="false" class="card-area">
    <div :class="advanced ? 'search' : null">
      <!-- 搜索区域 -->
      <a-form layout="horizontal">
        <div :class="advanced ? null: 'fold'">
          <a-row>

            <a-col :md="12" :sm="24" >
              <a-form-item
                label="法人行"
                :labelCol="{span: 5}"
                :wrapperCol="{span: 18, offset: 1}">
                <a-select v-if="this.user.admin"
                  mode="default"
                  :allowClear="true"
                  style="width: 100%"
                  @change="handleInstChange"
                  v-model="queryParams.instId">
                  <a-select-option v-for="r in instIdData" :key="r.label">{{r.label}}-{{r.value}}</a-select-option>
                </a-select>
                <a-input v-if="!this.user.admin" v-model="queryParams.instId" :value="this.user.instId" :disabled="true"/>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-show="queryParams.instId!=''">
            <a-col :md="12" :sm="24" >
              <a-form-item
                label="权限按钮名称"
                :labelCol="{span: 5}"
                :wrapperCol="{span: 18, offset: 1}">
                <!--<a-input v-model="queryParams.menuName"/>-->

<!--                <a-select
                  mode="default"
                  label-in-value
                  placeholder="选择权限按钮"
                  style="width: 100%"
                  :filter-option="false"
                  :not-found-content="fetching ? undefined : null"
                  @search="fetchButton"
                  v-model="queryParams.perms"
                >
                  <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                  <a-select-option v-for="d in menuData" :key="d.permission">
                    {{ d.text }}- {{d.permission}}
                  </a-select-option>
                </a-select>-->

                <pagination-search-select v-model="queryParams.perms" :listUrl="getMenuListUrl" :listUrlParam="menuListUrlParam" valueName="perms" :showNameArr="showNameArr"
                                          :pageSize="10" :openSearch="true" :searchWordKeyArr="searchWorldKey" placeholder="">

                </pagination-search-select>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <div style="text-align: center;" v-show="queryParams.instId!=''">
          <a-button type="primary" @click="search">查询</a-button>
          <a-button style="margin-left: 8px" @click="reset">重置</a-button>
        </div>
      </a-form>
    </div>
    <div v-show="queryParams.instId!=''">
      <div class="operator">
        <a-button v-hasPermission="['privilegecheck:add']" ghost type="primary" @click="add">新增</a-button>
        <!--<a-button v-hasPermission="['privilegecheck:delete']" @click="batchDelete">删除</a-button>-->
        <a-dropdown v-hasPermission="['privilegecheck:export']">
          <a-menu slot="overlay">
            <a-menu-item key="export-data" @click="exprotExccel">导出Excel</a-menu-item>
          </a-menu>
          <a-button>
            更多操作 <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </div>
      <!-- 表格区域 -->
      <a-table ref="TableInfo"
               :columns="columns"
               :rowKey="record => record.id"
               :dataSource="dataSource"
               :pagination="pagination"
               :loading="loading"
               :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,type: 'radio'}"
               :scroll="{ x: 900 }"
               @change="handleTableChange">
        <template slot="remark" slot-scope="text, record">
          <a-popover placement="topLeft">
            <template slot="content">
              <div style="max-width: 200px">{{text}}</div>
            </template>
            <p style="width: 200px;margin-bottom: 0">{{text}}</p>
          </a-popover>
        </template>
        <template slot="operation" slot-scope="text, record">
          <a-icon v-hasPermission="['privilegecheck:update']" type="setting" theme="twoTone" twoToneColor="#4a9ff5" @click="edit(record)" title="修改"></a-icon>
          &nbsp;
          <a-icon type="eye" theme="twoTone" twoToneColor="#42b983" @click="view(record)" title="查看"></a-icon>
        </template>
      </a-table>
      <!-- 角色信息查看 -->
<!--      <privilegecheck-info
        @close="handlePrivilegeCheckInfoClose"
        :privilegecheckVisiable="privilegecheck.visiable"
        :privilegecheckData="privilegecheck.data"
        :roleInstId="queryParams.instId">
      </privilegecheck-info>-->
      <!-- 新增 -->
      <privilege-check-add
        ref="privilegeCheckAdd"
        @close="handlePrivilegeCheckAddClose"
        @success="handlePrivilegeCheckAddSuccess"
        :privilegeCheckAddVisiable="privilegeCheckAdd.visiable"
        :privilegeCheckInstId="queryParams.instId"
        :maxCheckLevel="maxCheckLevel"
      >
      </privilege-check-add>
      <!-- 修改 -->
      <privilege-check-edit
        ref="privilegeCheckEdit"
        :privilegeCheckData="privilegeCheck.data"
        @close="handlePrivilegeCheckEditClose"
        @success="handlePrivilegeCheckEditSuccess"
        :privilegeCheckEditVisiable="privilegeCheckEdit.visiable"
        :privilegeCheckInstId="queryParams.instId"
        :maxCheckLevel="maxCheckLevel">
      </privilege-check-edit>
      <!-- 查看 -->
      <privilege-check-info
        ref="privilegeCheckInfo"
        :privilegeCheckData="privilegeCheck.data"
        @close="handlePrivilegeCheckInfoClose"
        :privilegeCheckInfoVisiable="privilegeCheckInfo.visiable"
        :privilegeCheckInstId="queryParams.instId"
        :maxCheckLevel="maxCheckLevel">
      </privilege-check-info>
    </div>
  </a-card>
</template>

<script>
import PaginationSearchSelect from '@/components/select/PaginationSearchSelect'
import RangeDate from '@/components/datetime/RangeDate'
import PrivilegeCheckAdd from './PrivilegeCheckAdd'
// import PrivilegeCheckInfo from './PrivilegeCheckInfo'
import PrivilegeCheckEdit from './PrivilegeCheckEdit'
import PrivilegeCheckInfo from './PrivilegeCheckInfo'
import { mapState } from "vuex"

export default {
  name: 'PrivilegeCheck',
  components: {
      PaginationSearchSelect,
      RangeDate,
      // PrivilegeCheckInfo,
      PrivilegeCheckAdd,
      PrivilegeCheckEdit,
      PrivilegeCheckInfo
  },
  data () {
    return {
      getMenuListUrl:'admin/upmpmenu/permsPageList',
      showNameArr:['menuName','perms'],
      menuListUrlParam:{'type':'1','channelType':'00'},
      searchWorldKey:['menuName'],
      advanced: false,
      privilegeCheck: {
        visiable: false,
        data: {}
      },
      privilegeCheckAdd: {
        visiable: false
      },
      privilegeCheckEdit: {
        visiable: false
      },
      privilegeCheckInfo: {
          visiable: false
      },
      queryParams: {
        createTimeFrom: '',
        createTimeTo: '',
        instId:'',
        perms:''
      },
      dataSource: [],
      sortedInfo: null,
      paginationInfo: null,
      selectedRowKeys: [],
      maxCheckLevel:"1",
      pagination: {
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
      loading: false,
      instIdData:[],
      fetching: false,
      menuData:[],
      channelTypeData: []
    }
  },
  computed: {
    ...mapState({
        user: state => state.account.user
    }),
    columns () {
      let {filteredInfo} = this
      filteredInfo = filteredInfo || {}
      return [ {
          title: '所属渠道分类',
          dataIndex: 'channelType',
          width: 200,
          fixed: 'left',
          customRender: (text, row, index) => {
              for(let i =0;i< this.channelTypeData.length;i++){
                  let title = this.channelTypeData[i];
                  if(text === title.label){
                      return title.value;
                  }
              }
          },
          filters: ()=>{
              var filterOjbArr = [];
              for(let i =0;i< this.channelTypeData.length;i++){
                  let title = this.channelTypeData[i];
                  let filterOjb = {text:title.value,value:title.label};
                  filterOjbArr.push(filterOjb);
              }
              return filterOjbArr;
          },
          filterMultiple: false,
          filteredValue: filteredInfo.channelType || null,
          onFilter: (value, record) => record.channelType.includes(value)
      }, {
          title: '按钮名称',
          dataIndex: 'menuName',
          width: 200,
      }, {
          title: '权限标识',
          dataIndex: 'perms',
          width: 200,
      },{
        title: '审核级别',
        dataIndex: 'checkLevel',
          customRender: (text, row, index) => {
              switch (text) {
                  case 1:
                      return <a-tag color="cyan"> 第一层级 </a-tag>
                  case 2:
                      return <a-tag color="pink"> 第二层级 </a-tag>
                  case 3:
                      return <a-tag color="purple"> 第三层级 </a-tag>
                  default:
                      return text
              }
          }
          /*,
          filters: [
              {text: '第一层级', value: 1},
              {text: '第二层级', value: 2},
              {text: '第三层级', value: 3}
          ],
          filterMultiple: false,
          filteredValue: filteredInfo.checkLevel || null,
          onFilter: (value, record) => record.checkLevel.includes(value)*/
      },{
          title: '是否审核',
          dataIndex: 'checked',
          customRender: (text, row, index) => {
              switch (text) {
                  case 'Y':
                      return <a-tag color="cyan"> 是 </a-tag>
                  case 'N':
                      return <a-tag color="pink"> 否 </a-tag>
                  default:
                      return text
              }
          }
          /*,
          filters: [
              {text: '是', value: 'Y'},
              {text: '否', value: 'N'}
          ],
          filterMultiple: false,
          filteredValue: filteredInfo.checked || null,
          onFilter: (value, record) => record.checked.includes(value)*/
      },  {
          title: '审核角色',
          dataIndex: 'roleName'
      }, {
        title: '操作',
        dataIndex: 'operation',
        scopedSlots: { customRender: 'operation' }
      }]
    }
  },
  mounted () {
    this.getInstList();
    this.getChannelType();
    if(!this.user.admin){
        this.handleInstChange(this.user.instId);
    }
    /*this.$get('admin/upmporg/getInstList').then((r) => {
        this.instIdData = r.data
    });
    this.$get('admin/upmpmenu/getChannelType').then((r) => {
        this.channelTypeData = r.data;
    });*/
  },
  methods: {
    async getInstList(){
        const res = await this.$get('admin/upmporg/getInstList');
        this.instIdData = res.data
    },
    async getChannelType(){
        const res = await this.$get('admin/upmpmenu/getChannelType');
        this.channelTypeData = res.data
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    add () {
      this.privilegeCheckAdd.visiable = true
    },
    update (record) {
        this.privilegeCheckEdit.visiable = true;
        this.privilegeCheck.data = record;
        // this.$refs.privilegeCheckEdit.setFormValues(record);
    },
    handleInstChange(value){
        this.queryParams.instId = value;
        if(value!=""){
          this.search();
          // this.fetchButton("");
          this.getMaxCheckLevel(value);
        }
    },
    fetchButton(menuName){
        let upmpMenu = {}
        upmpMenu.type="1"
        if(""!=menuName){
            upmpMenu.menuName = menuName
            upmpMenu.perms = menuName
        }
        upmpMenu.channelType="00";
        this.$get('admin/upmpmenu',{
            ...upmpMenu
        }).then((r) => {
            this.menuData = r.data.rows;
        })
    },
    async getMaxCheckLevel(instId){
        this.$get('admin/upmpprivilegecheck/getMaxCheckLevel/'+instId).then((r) => {
            this.maxCheckLevel = r.data.data;
            console.log("maxCheckLevel:"+this.maxCheckLevel);
        })
    },
    handlePrivilegeCheckAddClose () {
      this.privilegeCheckAdd.visiable = false
    },
    handlePrivilegeCheckAddSuccess () {
      this.privilegeCheckAdd.visiable = false
      this.$message.success('新增权限审核配置成功')
      this.search()
    },
    view (record) {
        this.$refs.privilegeCheckInfo.setFormValues(record)
      this.privilegeCheck.data = record
      this.privilegeCheckInfo.visiable = true
    },
    handlePrivilegeCheckInfoClose () {
      this.privilegeCheckInfo.visiable = false
    },
    edit (record) {
      this.$refs.privilegeCheckEdit.setFormValues(record)
      this.privilegeCheck.data = record
      this.privilegeCheckEdit.visiable = true
    },
    handlePrivilegeCheckEditSuccess () {
      this.privilegeCheckEdit.visiable = false
      this.$message.success('修改权限审核配置成功')
      this.search()
    },
    handlePrivilegeCheckEditClose () {
      this.privilegeCheckEdit.visiable = false
    },
    handleDateChange (value) {
      if (value) {
        this.queryParams.createTimeFrom = value[0]
        this.queryParams.createTimeTo = value[1]
      }
    },
    batchDelete () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的记录')
        return
      }
      let that = this
      this.$confirm({
        title: '确定删除所选中的记录?',
        content: '当您点击确定按钮后，这些记录将会被彻底删除',
        centered: true,
        onOk () {
          let roleIds = []
          let selectedRowKeysStr = ',' + that.selectedRowKeys.join(',') + ','
          roleIds.push(that.dataSource.filter(f => { return selectedRowKeysStr.indexOf(',' + f.roleId + ',') > -1 }).map(m => { return m.roleId }))
          that.$delete('admin/upmpprivilegecheck/' + roleIds.join(',')).then(() => {
            that.$message.success('删除成功')
            that.selectedRowKeys = []
            that.search()
          })
        },
        onCancel () {
          that.selectedRowKeys = []
        }
      })
    },
    exprotExccel () {
      let {sortedInfo} = this
      let sortField, sortOrder
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field
        sortOrder = sortedInfo.order
      }
      this.$export('admin/upmpprivilegecheck/excel', {
        sortField: sortField,
        sortOrder: sortOrder,
        ...this.queryParams
      })
    },
   search () {
      let {sortedInfo} = this
      let sortField, sortOrder
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field
        sortOrder = sortedInfo.order
      }
      this.fetch({
        sortField: sortField,
        sortOrder: sortOrder,
        ...this.queryParams
      })
    },
    reset () {
      // 取消选中
      this.selectedRowKeys = []
      // 重置分页
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent
        this.paginationInfo.pageSize = this.pagination.defaultPageSize
      }
      // 重置列排序规则
      this.sortedInfo = null
      // 重置查询参数
      this.queryParams = {}
      this.queryParams.instId = "";
      // 清空时间选择
      // this.$refs.createTime.reset()

      if(!this.user.admin){
          this.handleInstChange(this.user.instId);
      }
    },
    handleTableChange (pagination, filters, sorter) {
      // 将这两个参数赋值给Vue data，用于后续使用
      this.paginationInfo = pagination
      this.sortedInfo = sorter
      this.fetch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...this.queryParams
      })
    },
    async fetch (params = {}) {
      this.loading = true
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
        params.pageSize = this.paginationInfo.pageSize
        params.pageNum = this.paginationInfo.current
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize
        params.pageNum = this.pagination.defaultCurrent
      }
      params.channelType='00'
      await this.$get('admin/upmpprivilegecheck', {
        ...params
      }).then((r) => {
        let data = r.data
        const pagination = { ...this.pagination }
        pagination.total = data.total
        this.dataSource = data.rows
        this.pagination = pagination
        this.loading = false
      })
    }
  }
}
</script>

<style lang="less" scoped>
@import "../../../../static/less/Common";
</style>
